import { platform } from '../App';
import { BehaviorSubject } from 'rxjs';
import { ISQLiteService } from './sqliteService';
import { IDbVersionService } from './dbVersionService';
import { SQLiteDBConnection } from '@capacitor-community/sqlite';
import { UserUpgradeStatements } from '../upgrades/user.upgrade.statements';
import { User } from '../models/User';
import { WaterLog } from '../models/WaterLog';
import { s } from 'vitest/dist/reporters-5f784f42';
import { FavoriteItem } from '../models/FavoriteItem';

export interface IStorageService {
    initializeDatabase(): Promise<void>
    getUsers(): Promise<User[]>
    addUser(user: User): Promise<number>
    updateUserById(id: string, active: number): Promise<void>
    deleteUserById(id: string): Promise<void>
    getDatabaseName(): string
    getDatabaseVersion(): number
    getWaterRecords(): Promise<WaterLog[]>
    insertWaterLog(water: WaterLog): Promise<number>
    deleteWaterLog(id: number): Promise<void>
    getAllFavorites(): Promise<FavoriteItem[]>
};
class StorageService implements IStorageService {
    versionUpgrades = UserUpgradeStatements;
    loadToVersion = UserUpgradeStatements[UserUpgradeStatements.length - 1].toVersion;
    db!: SQLiteDBConnection;
    database: string = 'myuserdb';
    sqliteServ!: ISQLiteService;
    dbVerServ!: IDbVersionService;
    isInitCompleted = new BehaviorSubject(false);

    constructor(sqliteService: ISQLiteService, dbVersionService: IDbVersionService) {
        this.sqliteServ = sqliteService;
        this.dbVerServ = dbVersionService;
    }
    async getAllFavorites(): Promise<FavoriteItem[]> {
        return (await [] as FavoriteItem[]);
    }

    async deleteWaterLog(id: number): Promise<void> {
        const sql = `DELETE FROM water_logs WHERE id=${id}`;
        await this.db.run(sql);
    }

    getDatabaseName(): string {
        return this.database;
    }
    getDatabaseVersion(): number {
        return this.loadToVersion;
    }
    async initializeDatabase(): Promise<void> {
        // create upgrade statements
        try {
            await this.sqliteServ.addUpgradeStatement({
                database: this.database,
                upgrade: this.versionUpgrades
            });
            this.db = await this.sqliteServ.openDatabase(this.database, this.loadToVersion, false);
            setTimeout(async () => {
                const res = await this.db.getTableList();
                console.log(`&&&& getTableList res ${JSON.stringify(res)}`)
            }, 1000);
            // const isData = await this.db.query("select * from sqlite_sequence");
            // // console.log(`&&&& sqlite_sequence res ${JSON.stringify(isData)}`)
            // if (isData.values!.length === 0) {
            //     // create database initial users if any

            // }
            this.dbVerServ.setDbVersion(this.database, this.loadToVersion);
            if (platform === 'web') {
                await this.sqliteServ.saveToStore(this.database);
            }
            this.isInitCompleted.next(true);
        } catch (error: any) {
            const msg = error.message ? error.message : error;
            throw new Error(`storageService.initializeDatabase: ${msg}`);
        }
    }
    async getUsers(): Promise<User[]> {
        return (await this.db.query('SELECT * FROM users;')).values as User[];
    }
    async addUser(user: User): Promise<number> {
        const sql = `INSERT INTO users (name) VALUES (?);`;
        const res = await this.db.run(sql, [user.name]);
        if (res.changes !== undefined
            && res.changes.lastId !== undefined && res.changes.lastId > 0) {
            return res.changes.lastId;
        } else {
            throw new Error(`storageService.addUser: lastId not returned`);
        }
    }
    async updateUserById(id: string, active: number): Promise<void> {
        const sql = `UPDATE users SET active=${active} WHERE id=${id}`;
        await this.db.run(sql);
    }
    async deleteUserById(id: string): Promise<void> {
        const sql = `DELETE FROM users WHERE id=${id}`;
        await this.db.run(sql);
    }



    //For water 
    async getWaterRecords(): Promise<WaterLog[]> {
        return (await this.db.query('SELECT * FROM water_logs;')).values as WaterLog[];
    }


    // 添加喝水记录
    async insertWaterLog(log: WaterLog): Promise<number> {
        try {
            const sql = `INSERT INTO water_logs (amount, timestamp) VALUES (?, ?);`
            const res = await this.db.run(sql, [log.amount, log.timestamp]);
            console.log(res)
            if (res.changes !== undefined
                && res.changes.lastId !== undefined && res.changes.lastId > 0) {
                return res.changes.lastId;
            } else {
                throw new Error(`storageService.addUser: lastId not returned`);
            }
        } catch (error) {
            console.log(error)
            return 0
        } finally {
            return 0
        }

    }

}
export default StorageService;
